<template>
    <el-dialog v-model="visible" :title="meterData?.meter_code + ' 表计数据'" width="80%" destroy-on-close draggable
        :close-on-click-modal="false">
        <div class="dialog-header">
            <div class="breadcrumb-container">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item v-for="item in breadcrumbList" :key="item.id"
                        :class="{ 'clickable': item.id !== currentMeter?.id }">
                        <el-button link @click="handleBreadcrumbClick(item)">{{ item.meter_code }}</el-button>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div style="margin-left: auto;">
                <span style="font-size: var(--font-size-small);margin-right: var(--gap-small);">表格布局</span>
                <el-segmented class="custom-style" v-model="localTableSize" :options="sizeOptions" />
            </div>
        </div>
        <vxe-table :row-config="{ isCurrent: true, isHover: true }" ref="tableRef" show-overflow :size="localTableSize"
            :style="{ fontSize: getFontSize() }" height="500px" border align="center" :data="childrenData"
            :loading="loading" @cell-click="handleTableRowClick">
            <!-- 固定列 -->
            <vxe-column fixed="left" type="seq" width="60" />
            <vxe-column fixed="left" field="meter_code" title="编号" :width="180">
                <template #default="{ row }">
                    <div class="meter-code-cell">
                        <span :class="{ 'current-meter': row.isCurrent }">{{ row.meter_code }}</span>
                        <el-tooltip v-if="!row.isCurrent && row.customChildren?.length" :content="getChildrenInfo(row)"
                            placement="right" :show-after="100">
                            <el-tag size="small" type="info" class="children-tag">
                                {{ row.customChildren.length }}个子表
                                <el-icon>
                                    <ArrowRight />
                                </el-icon>
                            </el-tag>
                        </el-tooltip>
                        <el-tag v-if="row.isCurrent" size="small" type="success">当前表计</el-tag>
                    </div>
                </template>
            </vxe-column>
            <vxe-column fixed="left" field="id" title="表号" :width="getCellWidth()" />
            <vxe-column field="specification" title="规格" :width="getCellWidth('spec')" />
            <vxe-column field="yesterday_reading" title="上次读数" :width="getCellWidth()"></vxe-column>
            <vxe-column field="current_reading" title="本次读数" :width="getCellWidth()"></vxe-column>
            <vxe-column field="current_reading_time" title="时间" :width="getCellWidth('time')">
                <template #default="{ row }">
                    {{ dayjs(row.current_reading_time).format('YYYY/MM/DD HH:mm:ss') }}
                </template>
            </vxe-column>
            <vxe-column field="Value" title="用量" :width="getCellWidth()">
                <template #default="{ row }">
                    {{ formatFlowValue(row.Value) }}
                </template>
            </vxe-column>
        </vxe-table>
    </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import dayjs from "dayjs";
import { formatFlowValue } from "@/utils/meterUtils";
import { ArrowRight } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
    visible: Boolean,
    meterData: Object,
    date: [Number, String],
    tableSize: String,
    loadChildNodes: {
        type: Function,
        required: true
    },
    fetchData: {
        type: Function,
        required: true
    }
});

const emit = defineEmits(['update:visible']);

// 组件状态
const visible = ref(false);
const loading = ref(false);
const childrenData = ref([]);
const tableRef = ref(null);
const breadcrumbList = ref([]);
const currentMeter = ref(null);

// 表格布局配置
const sizeOptions = [{ label: '紧凑', value: 'mini' }, { label: '标准', value: 'small' }, { label: '宽松', value: 'medium' }];
const localTableSize = ref(props.tableSize || 'small');

// 获取子表信息
const getChildrenInfo = (row) => {
    if (!row.customChildren?.length) return '';
    const childrenCodes = row.customChildren
        .map(child => child.meter_code)
        .join('\n');
    return `子表列表：\n${childrenCodes}`;
};

// 获取单元格宽度
const getCellWidth = (type) => {
    switch (localTableSize.value) {
        case 'mini':
            return type === 'time' ? 160 : type === 'spec' ? 80 : 100;
        case 'medium':
            return type === 'time' ? 200 : type === 'spec' ? 140 : 160;
        default:
            return type === 'time' ? 180 : type === 'spec' ? 100 : 120;
    }
};

// 获取字体大小
const getFontSize = () => {
    switch (localTableSize.value) {
        case 'mini':
            return '12px';
        case 'medium':
            return '18px';
        default:
            return '14px';
    }
};

// 处理面包屑点击
const handleBreadcrumbClick = (item) => {
    if (item.meter_code === currentMeter.value?.meter_code) return;

    const index = breadcrumbList.value.findIndex(i => i.meter_code === item.meter_code);
    if (index > -1) {
        breadcrumbList.value = breadcrumbList.value.slice(0, index + 1);
        currentMeter.value = item;
        loadMeterData(item);
    }
};

// 处理表格行点击
const handleTableRowClick = async ({ row }) => {
    if (!row.isCurrent && row.hasChild && row.customChildren?.length > 0) {
        currentMeter.value = row;
        breadcrumbList.value.push(row);
        await loadMeterData(row);
    }
};

// 加载表计数据
async function loadMeterData(meter) {
    if (!meter) return;

    loading.value = true;
    try {
        // 获取子表数据
        const children = await props.loadChildNodes(meter);

        // 组合数据，将当前表计数据放在最前面
        const combinedData = [
            { ...meter, isCurrent: true },
            ...children.map(child => ({ ...child, isCurrent: false }))
        ];

        childrenData.value = combinedData;
    } catch (error) {
        console.error('Failed to load meter data:', error);
        ElMessage.error('加载数据失败');
    } finally {
        loading.value = false;
    }
}

// 初始化加载数据
const loadChildData = async () => {
    if (!props.meterData) return;

    if (breadcrumbList.value.length === 0) {
        breadcrumbList.value = [props.meterData];
        currentMeter.value = props.meterData;
    }

    await loadMeterData(currentMeter.value);
};

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
    visible.value = newVal;
    breadcrumbList.value = [];
    if (newVal && props.meterData) {
        loadChildData();
    }
});

// 监听对话框关闭
watch(() => visible.value, (newVal) => {
    emit('update:visible', newVal);
});

</script>

<style scoped>
.dialog-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.breadcrumb-container {
    flex: 1;
}

.meter-code-cell {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: var(--gap-small);
}

.current-meter {
    font-weight: bold;
    color: var(--el-color-primary);
}

.children-tag {
    margin-left: 4px;
}

:deep(.clickable) {
    cursor: pointer;
}

:deep(.el-dialog__body) {
    padding-top: 10px;
}

:deep(.vxe-table--loading) {
    background-color: rgba(255, 255, 255, 0.9);
}

:deep(.custom-style) {
    --el-border-radius-round: 20px;
}

:deep(.el-dialog) {
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}
</style>